package com.lbt.msmservice.controller;


import com.aliyuncs.exceptions.ClientException;
import com.lbt.commonuntils.R;
import com.lbt.msmservice.service.MsmService;
import com.lbt.msmservice.untils.RandomUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Api(description = "阿里云短信发送业务")
@RestController
//@CrossOrigin
@RequestMapping("/edumsm/msm")
public class MsmController {
    @Autowired
    MsmService msmService;
    @Autowired
    RedisTemplate<String,String> redisTemplate;

    @ApiOperation("发送短信，五分钟有效")
    @GetMapping("/send/{phone}")
    public R SendSms(@PathVariable("phone") String phone ) {      //可以使用redis实现5分钟有效
        //先从redis中取数据 如果有则返回，没有就发送
       // redisTemplate.opsForValue().set("msg","1314111");
        String code = redisTemplate.opsForValue().get("phone");
        if(!StringUtils.isEmpty(code)){
            return R.ok();
        }
        code=RandomUtil.getSixBitRandom();
        Map<String,Object>map=new HashMap<>();
        map.put("code",code);
        boolean isSend=msmService.send(map,phone);
        if(isSend){
            //发送成功-----将code =>    存入redis    设置有效时间
            redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);
            return R.ok();
        }else {
            return R.error();
        }
    }

}
